<template>
	<a-modal
		v-model:open="visible"
		title="人员选择"
		:width="800"
		:mask-closable="false"
		:destroy-on-close="true"
		@ok="handleOk"
		@cancel="handleClose"
	>
		<div class="flex flex-row w-full">
			<div class="w-1/2 pr-2">
				<a-tabs v-model:activeKey="activeKey">
					<a-tab-pane key="1" tab="人员">
						<div class="search-box mb-3">
							<a-input-search
								v-model:value="searchKey"
								placeholder="请输入手机号或名字搜索"
								allow-clear
								@search="handleSearch"
							/>
						</div>
						<div class="tabs-content-container">
							<a-table
								size="small"
								:columns="userColumns"
								:data-source="userList"
								:pagination="{
									current: userCurrent,
									pageSize: userPageSize,
									total: userTotal,
									showSizeChanger: true,
									size: 'small'
								}"
								:row-key="(record) => record.id"
								:row-selection="{
									selectedRowKeys: selectedUserIds,
									onChange: handleUserSelectionChange
								}"
								@change="handleUserTableChange"
								:loading="userLoading"
								bordered
							>
								<template #bodyCell="{ column, record }">
									<template v-if="column.dataIndex === 'name'">
										<div class="flex items-center">
											<a-avatar :src="record.avatar" size="small" class="mr-2">
												<template #icon><UserOutlined /></template>
											</a-avatar>
											<span>{{ record.name }}</span>
										</div>
									</template>
								</template>
							</a-table>
						</div>
					</a-tab-pane>
					<a-tab-pane key="2" tab="角色">
						<div class="search-box mb-3">
							<a-input-search
								v-model:value="roleSearchKey"
								placeholder="请输入角色名称搜索"
								allow-clear
								@search="handleRoleSearch"
							/>
						</div>
						<div class="tabs-content-container">
							<a-table
								size="small"
								:columns="roleColumns"
								:data-source="roleList"
								:pagination="{
									current: roleCurrent,
									pageSize: rolePageSize,
									total: roleTotal,
									showSizeChanger: true,
									size: 'small'
								}"
								:row-key="(record) => record.id"
								:row-selection="{
									selectedRowKeys: selectedRoleIds,
									onChange: handleRoleSelectionChange
								}"
								@change="handleRoleTableChange"
								:loading="roleLoading"
								bordered
							>
								<template #bodyCell="{ column, record }">
									<template v-if="column.dataIndex === 'name'">
										<div class="flex items-center">
											<TeamOutlined class="mr-2 text-blue-500" />
											<span>{{ record.name }}</span>
										</div>
									</template>
								</template>
							</a-table>
						</div>
					</a-tab-pane>
					<a-tab-pane key="3" tab="部门">
						<div class="search-box mb-3">
							<a-input-search
								v-model:value="deptSearchKey"
								placeholder="请输入部门名称搜索"
								allow-clear
								@search="handleDeptSearch"
							/>
						</div>
						<div class="tabs-content-container tree-container">
							<a-spin :spinning="deptLoading">
								<a-tree
									v-if="deptTreeData.length > 0"
									:tree-data="deptTreeData"
									:fieldNames="{ children: 'children', title: 'name', key: 'id' }"
									:checkable="true"
									:multiple="true"
									:checkStrictly="true"
									:checked-keys="selectedDeptIds"
									@check="handleDeptTreeCheck"
									:height="380"
									show-icon
								>
									<template #title="{ name }">
										<div class="flex items-center">
											<ApartmentOutlined class="mr-2 text-green-500" />
											<span>{{ name }}</span>
										</div>
									</template>
								</a-tree>
								<a-empty v-else description="暂无部门数据" />
							</a-spin>
						</div>
					</a-tab-pane>
				</a-tabs>
			</div>

			<div class="w-1/2 pl-2 selected-area">
				<div class="flex justify-between items-center mb-2">
					<div class="font-bold">已选({{ selectedCount }})</div>
					<a-button type="link" @click="clearSelected">清空</a-button>
				</div>
				<div class="selected-items selected-items-container">
					<a-tag
						v-for="item in selectedUserItems"
						:key="'user-' + item.id"
						closable
						@close="removeSelected('user', item.id)"
					>
						<UserOutlined class="mr-1" /> {{ item.name }}
					</a-tag>
					<a-tag
						v-for="item in selectedRoleItems"
						:key="'role-' + item.id"
						closable
						@close="removeSelected('role', item.id)"
					>
						<TeamOutlined class="mr-1" /> {{ item.name }}
					</a-tag>
					<a-tag
						v-for="item in selectedDeptItems"
						:key="'dept-' + item.id"
						closable
						@close="removeSelected('dept', item.id)"
					>
						<ApartmentOutlined class="mr-1" /> {{ item.name }}
					</a-tag>
				</div>
			</div>
		</div>
	</a-modal>
</template>

<script setup>
	import { ref, computed, watch } from 'vue'
	import { message } from 'ant-design-vue'
	import { UserOutlined, TeamOutlined, ApartmentOutlined } from '@ant-design/icons-vue'
	import userApi from '@/api/sys/userApi'
	import roleApi from '@/api/sys/roleApi'
	import orgApi from '@/api/sys/orgApi'

	// 弹窗是否打开
	const visible = ref(false)
	const activeKey = ref('1')

	// 当前选中的权限组
	const currentGroup = ref(null)

	// 用户列表相关
	const userList = ref([])
	const userTotal = ref(0)
	const userCurrent = ref(1)
	const userPageSize = ref(10)
	const searchKey = ref('')
	const selectedUserIds = ref([])
	const userLoading = ref(false)

	// 角色列表相关
	const roleList = ref([])
	const roleTotal = ref(0)
	const roleCurrent = ref(1)
	const rolePageSize = ref(10)
	const roleSearchKey = ref('')
	const selectedRoleIds = ref([])
	const roleLoading = ref(false)

	// 部门列表相关
	const deptSearchKey = ref('')
	const selectedDeptIds = ref([])
	const deptLoading = ref(false)

	// 已选择的项目
	const selectedUserItems = ref([])
	const selectedRoleItems = ref([])
	const selectedDeptItems = ref([])

	// 计算已选择的总数
	const selectedCount = computed(() => {
		return selectedUserItems.value.length + selectedRoleItems.value.length + selectedDeptItems.value.length
	})

	// 用户表格列定义
	const userColumns = [
		{
			dataIndex: 'account',
			title: '账号'
		},
		{
			dataIndex: 'name',
			title: '姓名'
		}
	]

	// 角色表格列定义
	const roleColumns = [
		{
			dataIndex: 'name',
			title: '角色名称'
		}
	]

	// 加载用户列表
	const loadUserList = async () => {
		try {
			userLoading.value = true
			const params = {
				current: userCurrent.value,
				size: userPageSize.value,
				searchKey: searchKey.value
			}
			const res = await userApi.userSelector(params)
			userList.value = res.records || []
			userTotal.value = res.total || 0
		} catch (error) {
			console.error('加载用户列表失败:', error)
		} finally {
			userLoading.value = false
		}
	}

	// 加载角色列表
	const loadRoleList = async () => {
		try {
			roleLoading.value = true
			const params = {
				current: roleCurrent.value,
				size: rolePageSize.value,
				searchKey: roleSearchKey.value
			}
			const res = await roleApi.roleRoleSelector(params)
			roleList.value = res.records || []
			roleTotal.value = res.total || 0
		} catch (error) {
			console.error('加载角色列表失败:', error)
		} finally {
			roleLoading.value = false
		}
	}

	// 部门树数据
	const deptTreeData = ref([])

	// 加载部门树数据
	const loadDeptTree = async () => {
		try {
			deptLoading.value = true
			const params = {
				searchKey: deptSearchKey.value
			}
			const res = await orgApi.orgTree(params)
			deptTreeData.value = res || []
		} catch (error) {
			console.error('加载部门树失败:', error)
		} finally {
			deptLoading.value = false
		}
	}

	// 监听标签页切换
	watch(activeKey, (newVal) => {
		if (newVal === '1') {
			loadUserList()
		} else if (newVal === '2') {
			loadRoleList()
		} else if (newVal === '3') {
			loadDeptTree()
		}
	})

	// 搜索用户
	const handleSearch = () => {
		userCurrent.value = 1
		loadUserList()
	}

	// 搜索角色
	const handleRoleSearch = () => {
		roleCurrent.value = 1
		loadRoleList()
	}

	// 搜索部门
	const handleDeptSearch = () => {
		loadDeptTree()
	}

	// 用户表格变化（分页、排序、筛选）
	const handleUserTableChange = (pagination) => {
		userCurrent.value = pagination.current
		userPageSize.value = pagination.pageSize
		loadUserList()
	}

	// 角色表格变化（分页、排序、筛选）
	const handleRoleTableChange = (pagination) => {
		roleCurrent.value = pagination.current
		rolePageSize.value = pagination.pageSize
		loadRoleList()
	}

	// 用户选择变化
	const handleUserSelectionChange = (selectedRowKeys) => {
		// 找出新增的用户ID
		const newIds = selectedRowKeys.filter((id) => !selectedUserItems.value.some((item) => item.id === id))
		// 找出需要从已选列表中移除的用户
		const removeIds = selectedUserItems.value
			.filter((item) => !selectedRowKeys.includes(item.id))
			.map((item) => item.id)

		// 添加新选择的用户到已选列表
		newIds.forEach((id) => {
			const user = userList.value.find((u) => u.id === id)
			if (user) {
				selectedUserItems.value.push({
					id: user.id,
					name: user.name,
					type: 'user'
				})
			}
		})

		// 从已选列表中移除取消选择的用户
		removeIds.forEach((id) => {
			const index = selectedUserItems.value.findIndex((item) => item.id === id)
			if (index !== -1) {
				selectedUserItems.value.splice(index, 1)
			}
		})

		selectedUserIds.value = selectedRowKeys
	}

	// 角色选择变化
	const handleRoleSelectionChange = (selectedRowKeys) => {
		// 找出新增的角色ID
		const newIds = selectedRowKeys.filter((id) => !selectedRoleItems.value.some((item) => item.id === id))
		// 找出需要从已选列表中移除的角色
		const removeIds = selectedRoleItems.value
			.filter((item) => !selectedRowKeys.includes(item.id))
			.map((item) => item.id)

		// 添加新选择的角色到已选列表
		newIds.forEach((id) => {
			const role = roleList.value.find((r) => r.id === id)
			if (role) {
				selectedRoleItems.value.push({
					id: role.id,
					name: role.name,
					type: 'role'
				})
			}
		})

		// 从已选列表中移除取消选择的角色
		removeIds.forEach((id) => {
			const index = selectedRoleItems.value.findIndex((item) => item.id === id)
			if (index !== -1) {
				selectedRoleItems.value.splice(index, 1)
			}
		})

		selectedRoleIds.value = selectedRowKeys
	}

	// 部门树选择变化
	const handleDeptTreeCheck = (checkedKeys, e) => {
		// 使用checked参数，包含当前选中的节点
		const checkedNodes = checkedKeys.checked || checkedKeys

		// 找出新增的部门ID
		const newIds = checkedNodes.filter((id) => !selectedDeptItems.value.some((item) => item.id === id))
		// 找出需要从已选列表中移除的部门
		const removeIds = selectedDeptItems.value.filter((item) => !checkedNodes.includes(item.id)).map((item) => item.id)

		// 添加新选择的部门到已选列表
		newIds.forEach((id) => {
			// 在树中查找对应的部门节点
			const findDeptNode = (nodes) => {
				for (const node of nodes) {
					if (node.id === id) {
						return node
					}
					if (node.children && node.children.length > 0) {
						const found = findDeptNode(node.children)
						if (found) return found
					}
				}
				return null
			}

			const dept = findDeptNode(deptTreeData.value)
			if (dept) {
				selectedDeptItems.value.push({
					id: dept.id,
					name: dept.name,
					type: 'dept'
				})
			}
		})

		// 从已选列表中移除取消选择的部门
		removeIds.forEach((id) => {
			const index = selectedDeptItems.value.findIndex((item) => item.id === id)
			if (index !== -1) {
				selectedDeptItems.value.splice(index, 1)
			}
		})

		// 更新选中的部门ID列表
		selectedDeptIds.value = checkedNodes
	}

	// 移除已选项
	const removeSelected = (type, id) => {
		if (type === 'user') {
			const index = selectedUserItems.value.findIndex((item) => item.id === id)
			if (index !== -1) {
				selectedUserItems.value.splice(index, 1)
				// 同时更新选中状态
				const idIndex = selectedUserIds.value.indexOf(id)
				if (idIndex !== -1) {
					selectedUserIds.value.splice(idIndex, 1)
				}
			}
		} else if (type === 'role') {
			const index = selectedRoleItems.value.findIndex((item) => item.id === id)
			if (index !== -1) {
				selectedRoleItems.value.splice(index, 1)
				// 同时更新选中状态
				const idIndex = selectedRoleIds.value.indexOf(id)
				if (idIndex !== -1) {
					selectedRoleIds.value.splice(idIndex, 1)
				}
			}
		} else if (type === 'dept') {
			const index = selectedDeptItems.value.findIndex((item) => item.id === id)
			if (index !== -1) {
				selectedDeptItems.value.splice(index, 1)
				// 同时更新选中状态
				const idIndex = selectedDeptIds.value.indexOf(id)
				if (idIndex !== -1) {
					selectedDeptIds.value.splice(idIndex, 1)
				}
			}
		}
	}

	// 清空所有已选
	const clearSelected = () => {
		selectedUserItems.value = []
		selectedRoleItems.value = []
		selectedDeptItems.value = []
		selectedUserIds.value = []
		selectedRoleIds.value = []
		selectedDeptIds.value = []
	}

	// 打开弹窗
	const showModal = (group) => {
		currentGroup.value = group
		visible.value = true

		// 初始化已选项
		if (group.members) {
			// 初始化已选用户
			selectedUserItems.value = group.members.filter((m) => m.type === 'user')
			selectedUserIds.value = selectedUserItems.value.map((item) => item.id)

			// 初始化已选角色
			selectedRoleItems.value = group.members.filter((m) => m.type === 'role')
			selectedRoleIds.value = selectedRoleItems.value.map((item) => item.id)

			// 初始化已选部门
			selectedDeptItems.value = group.members.filter((m) => m.type === 'dept')
			selectedDeptIds.value = selectedDeptItems.value.map((item) => item.id)
		} else {
			clearSelected()
		}

		// 加载初始数据
		if (activeKey.value === '1') {
			loadUserList()
		} else if (activeKey.value === '2') {
			loadRoleList()
		} else if (activeKey.value === '3') {
			loadDeptTree()
		}
	}

	// 确认选择
	const handleOk = () => {
		if (currentGroup.value) {
			// 合并所有已选项
			const allSelected = [...selectedUserItems.value, ...selectedRoleItems.value, ...selectedDeptItems.value]

			// 更新当前权限组的成员
			currentGroup.value.members = allSelected

			message.success('添加成功')
		}
		visible.value = false
	}

	// 关闭弹窗
	const handleClose = () => {
		visible.value = false
	}

	// 暴露方法
	defineExpose({
		showModal
	})
</script>

<style scoped>
	.selected-items {
		min-height: 60px;
		padding: 8px;
		border: 1px solid #f0f0f0;
		border-radius: 2px;
	}

	.selected-items .ant-tag {
		margin-bottom: 8px;
	}

	.tabs-content-container {
		height: 400px;
		overflow: hidden;
	}

	.tree-container {
		padding: 4px;
		overflow: auto;
	}

	.selected-items-container {
		height: 400px;
		overflow-y: auto;
	}

	.selected-area {
		display: flex;
		flex-direction: column;
		height: 100%;
	}

	:deep(.ant-table-wrapper) {
		margin-bottom: 0;
	}

	:deep(.ant-table-pagination) {
		margin: 8px 0;
	}

	:deep(.ant-table-thead > tr > th) {
		padding: 8px;
	}

	:deep(.ant-table-tbody > tr > td) {
		padding: 4px 8px;
	}

	:deep(.ant-tree) {
		max-height: 380px;
		overflow: auto;
	}
</style>
